<template>
  <a-select v-model:value="trainCode" show-search
            :filter-option="filterTrainCodeOption" placeholder="请选择车次"
            @change="onChange" :style="'width:' + _width">

    <a-select-option v-for="item in trains" :key="item.code"
                     :value="item.code" :label="item.code + item.start + item.end">
      {{item.code}} | {{item.start}} ~ {{item.end}}
    </a-select-option>

  </a-select>
</template>

<script>
import {defineComponent, onMounted, ref, watch} from 'vue';
import axios from "axios";
import {notification} from "ant-design-vue";
export default defineComponent({
  name: "train-select-view",
  props:["modelValue","wdith"],
  emits:['update:modelValue','change'],
  setup(props, {emit}) {
    const trainCode = ref();

    const _width = ref(props.wdith);
    if(Tool.isEmpty(props.wdith)) {
      _width.value = "100%";
    }
    /**
     * 获取所有火车车次,用于车位下拉框
     */

    //利用watch，动态获取父组件的值，如果放在onMounted或其他方法只会执行一次
    watch(() => props.modelValue, ()=>{
          console.log("props.modelValue",props.modelValue)
          trainCode.value = props.modelValue;
    },{immediate: true})

    const trains = ref([]);

    const queryTrain = () =>{
      // if(Tool.isNotEmpty(SESSION_STATION_PARAMS)) {
      //   console.log("缓存读取")
      //   let list = SessionStorage.get(SESSION_STATION_PARAMS);
      //   trains.value = list;
      // }else {
        axios.get("/business/admin/train/query-all").then((response) => {
          const data = response.data;
          if (data.success) {
            console.log("数据库读取");
            trains.value = data.content;
            SessionStorage.set(SESSION_STATION_PARAMS,data.content);
          } else {
            notification.error({description: data.message});
          }
        })
      //}
    }
    /**
     * 车位下拉框筛选
     */
    const filterTrainCodeOption = (input, option) => {
      console.log(input,option);
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    }

    /**
     * 将当前组件的值响应给父组件
     * @param value
     */
    const onChange = (value) => {
      emit('update:modelValue', value);
      let train = trains.value.filter(item => item.code === value)[0];
      if (Tool.isEmpty(train)) {
        train = {};
      }
      emit('change', train);
    };

    onMounted(() => {
      queryTrain()
    })
    return {
      trains,
      queryTrain,
      filterTrainCodeOption,
      trainCode,
      onChange,
      _width
    };
  },
});
</script>

<style>

</style>